package com.itheima.health.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.itheima.health.common.RedisConst;
import com.itheima.health.common.RocketMQConst;
import com.itheima.health.message.SendOrderShowRocketMQ;
import com.itheima.health.message.SendValidateRocketMQ;
import com.itheima.health.service.SmsRocketMQService;
import com.itheima.health.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.security.SecureRandom;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@DubboService
public class SmsServiceImpl implements SmsRocketMQService {

    private IAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>"));

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void sendValidateCode(String validateCodeType, String phone) {
        /*
         * @Date: 4:52 下午 2021/1/10
         * @param: [validateCodeType, phone]
         * @return: void
         * @Description: 随机生成验证码，并把验证码存入redis中
         */
        log.info("[短信-发送验证码] - type:{} - phone:{}", validateCodeType, phone);
        // 生成验证码（1000~9999）
        int code = (int) (1000 + new SecureRandom().nextDouble() * 8999);
        //String code = "1234";
        log.info("[短信-发送验证码] - code:{}", code);
        //把验证码存入redis中（5*60L, TimeUnit.SECONDS生效时间）

        if (validateCodeType.equals("MOBILE_SIGNIN")) {
            redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PREFIX + "MOBILE_SIGNIN" + phone).set(String.valueOf(code), 5 * 60L, TimeUnit.SECONDS);
            String sms = "【传智健康】 验证码" + code + "仅供用户" + phone + "登录或注册使用,五分钟内有效!";
            rocketMQTemplate.convertAndSend(RocketMQConst.TOPIC_SMS_SEND, new SendValidateRocketMQ(sms));
        }
        if (validateCodeType.equals("ORDER")) {
            redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PREFIX + "ORDER" + phone).set(String.valueOf(code), 5 * 60L, TimeUnit.SECONDS);
            String order = "【传智健康】 验证码" + code + "仅供用户" + phone + "提交订单使用,五分钟内有效!";
            rocketMQTemplate.convertAndSend(RocketMQConst.TOPIC_ORDER_SEND, new SendValidateRocketMQ(order));
        }

        //阿里短信服务示例代码，不需要更改,用来给用户发送后端生成的验证码
//        CommonRequest request = new CommonRequest();
//        request.setSysMethod(MethodType.POST);
//        request.setSysDomain("dysmsapi.aliyuncs.com");
//        request.setSysVersion("2017-05-25");
//        request.setSysAction("SendSms");
//        request.putQueryParameter("RegionId", "cn-hangzhou");
//        request.putQueryParameter("PhoneNumbers", phone);
//        request.putQueryParameter("SignName", "传智健康");
//        request.putQueryParameter("TemplateCode", "SMS_209171113");
//        request.putQueryParameter("TemplateParam", "{\"assertCode\":\"1234\"}");
//        try {
//            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
//        } catch (ServerException e) {
//            e.printStackTrace();
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }
    }


    /**
     * @Author: Administrator
     * @Date: 19:38 2021/1/19
     * @Params: [map]
     * @ReturnType: void
     * @Description: 将用户提交的订单信息以短信的方式发送给客户
     */
    @Override
    public void sendOrderShow(Map<String, Object> map) {
        log.info("[短信-订单回显信息]map:{}", map);
        String member = (String) map.get("member");
        String setmeal = (String) map.get("setmeal");
        String orderDate = (String) map.get("orderDate");
        String orderType = (String) map.get("orderType");
        String hint = "【传智健康】 会员预约信息:" + member +" "+ setmeal +" "+ orderDate +" "+ orderType;
        rocketMQTemplate.convertAndSend(RocketMQConst.TOPIC_ORDER_SHOW_SEND, new SendOrderShowRocketMQ(hint));

    }

    @Override
    public boolean checkValidateCode(String phone, String code,String type) {
        /*
         * @Date: 5:08 下午 2021/1/10
         * @param: [phone, code]
         * @return: boolean
         * @Description: 前后端检查验证码是否一致
         * 1、判断redis中的code与上传的code是否一致（防止别人使用虚假验证码进行恶意破坏）
         * 2、一致则返回true并删除redis中的key，不一致返回false（防止前后端验证码不一致）
         */
        boolean flag = false;
        //redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PREFIX + "" + phone).set("1234");

        if (type.equals("MOBILE_SIGNIN")){
            Object objCode = redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PREFIX + "MOBILE_SIGNIN" + phone).get();
            String redisCode = String.valueOf(objCode);
            log.info("[短信-验证码] - 前端上传code: {} - redis中的code: {}", code, redisCode);
            //判断redis中的code与上传的code是否一样
            if (!StringUtils.isEmpty(objCode) && redisCode.equals(code)) {
                flag = true;
                //如果一样则把key从redis中删除
                redisTemplate.delete(RedisConst.VALIDATE_CODE_PREFIX + "MOBILE_SIGNIN" + phone);
            }
        }
        if (type.equals("ORDER")){
            Object objCode = redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PREFIX + "ORDER" + phone).get();
            String redisCode = String.valueOf(objCode);
            log.info("[短信-验证码] - 前端上传code: {} - redis中的code: {}", code, redisCode);
            //判断redis中的code与上传的code是否一样
            if (!StringUtils.isEmpty(objCode) && redisCode.equals(code)) {
                flag = true;
                //如果一样则把key从redis中删除
                redisTemplate.delete(RedisConst.VALIDATE_CODE_PREFIX + "ORDER" + phone);
            }
        }




        return flag;
    }


}
